package com.fmync.ai.fmync.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

public class FileUploadUtil {

    public static String saveFile(MultipartFile file, String uploadDir) throws IOException {
        // 确保上传目录存在
        Path uploadPath = Paths.get(uploadDir);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        // 生成唯一的文件名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String uniqueFileName = UUID.randomUUID().toString() + extension;

        // 构建完整的文件路径
        Path filePath = uploadPath.resolve(uniqueFileName);

        // 保存文件
        file.transferTo(filePath.toFile());

        return uploadDir+ File.separator+uniqueFileName;
    }
}
